﻿//========================================
// All rights reserved (C) 2017-2100
// CLR 版本：	4.0.30319.42000
// 命名空间:	Network.UpdateData
// 文 件 名：	PacketHandle
// 作    者：	WooG
// 联系方式：	wooglle@163.com
// 创建时间：	2017/9/27 14:46:31
//========================================
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Network.UpdateData
{
    public abstract class PacketHandle
    {
        public const int msgInPort = 65401;
        public const int udpInPort = 65402;
        protected int code;
        protected Guid guidSend;
        protected Int32 ipSend;
        protected Guid guidTarget;
        protected string Message;
        protected Socket socket;
        
        public PacketHandle(Socket socket, Packet packet)
        {
            this.socket = socket;
            code = packet.Code;
            guidSend = packet.GuidSend;
            ipSend = packet.IpSend;
            guidTarget = packet.GuidTarget;
            Message = packet.Message;
            //new Thread(() =>
            //{
                try
                {
                    Handle();
                }
                catch
                {
                    throw;
                    //try
                    //{
                    //    File.AppendAllText(Path.GetTempPath() + "SFJD\\Erro.txt", "[" + DateTime.Now.ToString("MMdd HH:mm:ss") + "]" + GetType().Name + " " + e.Message + "\r\n");
                    //}
                    //catch
                    //{
                    //    Directory.CreateDirectory(Path.GetTempPath() + "/SFJD");
                    //    File.AppendAllText(Path.GetTempPath() + "SFJD\\Erro.txt", "[" + DateTime.Now.ToString("MMdd HH:mm:ss") + "]" + GetType().Name + " " + e.Message + "\r\n");
                    //}
                }
                finally
                {
                    if (this.socket != null && this.socket.Connected)
                    {
                        this.socket.Close();
                    }
                }
            //}).Start();
        }

        protected abstract void Handle();

        protected void Delay(int milliSecond)
        {
            Thread.Sleep(milliSecond);
        }

        /// <summary>
        /// 向等待消息的连接返回消息
        /// </summary>
        /// <param name="code">消息代码</param>
        /// <param name="guidSend">发送方GUID</param>
        /// <param name="msgBack">消息内容</param>
        protected void SendTcpBack(int code, Guid guidSend, string msgBack)
        {
            if(socket == null || !socket.Connected)
            {
                return;
            }
            Packet packet = new Packet((Int16)code, guidSend, msgBack);
            socket.Send(packet.ToBytes());
        }

        protected string GetIpSend()
        {
            return new IPAddress(BitConverter.GetBytes(ipSend)).ToString();
        }
    }
}
